import Taro from "@tarojs/taro";

/**
 * @typedef {Object} RequestOptions
 * @property {string} url - 请求地址
 * @property {any} [data] - 请求参数
 * @property {"GET"|"POST"|"PUT"|"DELETE"} [method] - 请求方法
 * @property {Record<string, string>} [header] - 请求头
 * @property {number} [timeout] - 超时时间（毫秒）
 * @property {boolean} [showErrorToast] - 是否自动弹出错误提示
 */

const DEFAULT_TIMEOUT = 10000; // 10秒
export const BASE_URL = "https://nengliguangchang.suchi.hongyutiancheng.com";

/**
 * 统一请求封装，自动添加token，超时处理，统一错误提示
 * @template T
 * @param {RequestOptions} options
 * @returns {Promise<T>}
 */
export function request<T = any>(options: any): Promise<T> {
  const { url, data = {}, method = "GET", header = {}, timeout = DEFAULT_TIMEOUT, showErrorToast = true, ...rest } = options;

  return new Promise<T>((resolve, reject) => {
    // 从本地获取token
    const token = Taro.getStorageSync("token");
    const finalHeader = {
      "Content-Type": "application/json",
      ...header,
      ...(token ? { token: token } : {}),
    };

    let timer: NodeJS.Timeout | number | null = null;
    let isTimeout = false;

    timer = setTimeout(() => {
      isTimeout = true;
      if (showErrorToast) {
        Taro.showToast({ title: "请求超时，请重试", icon: "none" });
      }
      reject(new Error("请求超时"));
    }, timeout);

    Taro.request({
      url,
      data,
      method,
      header: finalHeader,
      ...rest,
      success(res) {
        if (isTimeout) return;
        clearTimeout(timer as NodeJS.Timeout);
        if (res.statusCode >= 200 && res.statusCode < 300) {
          resolve(res.data as T);
        } else {
          if (showErrorToast) {
            Taro.showToast({ title: res.data?.msg || "请求失败", icon: "none" });
          }
          // 401处理
          if (res.statusCode === 401) {
            Taro.removeStorageSync("token");
            Taro.redirectTo({ url: "/pages/webs/register" });
          }
          reject(res);
        }
      },
      fail(err) {
        if (isTimeout) return;
        clearTimeout(timer as NodeJS.Timeout);
        if (showErrorToast) {
          Taro.showToast({ title: "网络异常", icon: "none" });
        }
        reject(err);
      },
    });
  });
}

/**
 * GET 请求
 */
export function get<T = any>(url: string, data?: any, options: Partial<any> = {}) {
  return request<T>({ url, data, method: "GET", ...options });
}

/**
 * POST 请求
 */
export function post<T = any>(url: string, data?: any, options: Partial<any> = {}) {
  return request<T>({ url, data, method: "POST", ...options });
}

/**
 * PUT 请求
 */
export function put<T = any>(url: string, data?: any, options: Partial<any> = {}) {
  return request<T>({ url, data, method: "PUT", ...options });
}

/**
 * DELETE 请求
 */
export function del<T = any>(url: string, data?: any, options: Partial<any> = {}) {
  return request<T>({ url, data, method: "DELETE", ...options });
}

/**
 * 性能优化说明：
 * 1. 采用Promise+超时定时器，防止接口卡死页面。
 * 2. 统一错误提示，减少重复代码。
 * 3. 自动注入token，便于权限接口调用。
 * 4. 支持自定义header、超时、toast等参数，灵活扩展。
 */
